package com.fzq.server.controller;

import com.fzq.client.ProductFeign;
import com.fzq.common.DescreaseStockInput;
import com.fzq.common.ProductInfoOutput;
import com.fzq.server.dataObject.ProductCategory;
import com.fzq.server.dataObject.ProductInfo;
import com.fzq.server.service.ProductCategoryService;
import com.fzq.server.service.ProductService;
import com.fzq.server.utils.ResultVOUtil;
import com.fzq.server.vo.ProductInfoVO;
import com.fzq.server.vo.ProductVO;
import com.fzq.server.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    public ResultVO<ProductVO> list() {

        List<ProductInfo> productInfoList = productService.findUpAll();
        List<ProductVO> productVOList = new ArrayList<>();
        List<Integer> types = productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> categoryList = productCategoryService.findByCategoryTypeIn(types);
        for (ProductCategory productCategory : categoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();

            for (ProductInfo productInfo : productInfoList
            ) {
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultVOUtil.success(productVOList);
    }

    @PostMapping("/listfororder")
    public List<ProductInfoOutput> listForOrder(@RequestBody List<String> ids) {
        return productService.findList(ids);
    }

    @PostMapping("/descreasestock")
    public void decreaseStock(@RequestBody List<DescreaseStockInput> descreaseStockInputList) {

        productService.descreaseStock(descreaseStockInputList);

    }

}
